import axios from 'axios'
import { ElMessage } from 'element-plus'
import { isTokenTimeout } from '@/utils/auth'
import store from '@/store'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
// 设置请求拦截器
service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      if (isTokenTimeout()) {
        // console.log('token失效, 主动退出')
        store.dispatch('user/loginOut')
        return Promise.reject(new Error('token 失效'))
      }
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    config.headers['Accept-Language'] = store.getters.language
    return config
  },
  (error) => {
    return Promise.reject(error.message)
  }
)

service.interceptors.request.use((config) => {
  config.headers.icode = 'helloqianduanxunlianying'
  return config // 必须返回配置
})

service.interceptors.response.use(
  (response) => {
    const { message, data, success } = response.data
    if (success) {
      return data
    } else {
      // 业务失败
      ElMessage.error(message)
      return Promise.reject(new Error(message))
    }
  },
  (error) => {
    if (
      error.response &&
      error.response.data &&
      error.response.data.code === 401
    ) {
      // token过期
      store.dispatch('user/loginOut')
    }
    return ElMessage.error(error.message || '接口请求失败')
  }
)

export default service
